/*
 * 李宇版权所有 
 */
package com.zbdx.util;

import java.io.IOException;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 *	数据库连接类
 * @author liyu
 * @version 1.0
 */
public class DBUtil {
	static DataSource ds;
	// stastic在类加载的时候就要执行;往JVM里加载
	//在static块里，不能使用非static属性
	static {
		Properties pro = new Properties();
		//配置目录必须放在src目录下
		InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
		//读取配置文件,把文件内容读到pro对象中
		try {
			pro.load(in);
			try {
				ds = DruidDataSourceFactory.createDataSource(pro);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取数据库连接
	 * @return 数据库连接对象
	 */
	public static Connection getConnection() {
		Connection conn = null;
		//从连接池中取连接
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	/**
	 * 关闭数据库资源
	 * @param rs 结果集
	 * @param pstmst 预编译对象
	 * @param conn 数据库连接
	 */
	
	public static void closeResource(ResultSet rs,PreparedStatement pstmst,Connection conn) {
		try {
			if(rs!=null) {
				rs.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (pstmst!=null) {
				pstmst.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if (conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		Connection conn = DBUtil.getConnection();
	    System.out.println(conn);
	}

}
